import sys

import pygame
import time
from constants import Constants
from text_box import TextBoxManager
class DrawManager:
    """负责所有绘制操作的类"""

    def __init__(self, resources, game_data, ui_components, game_state):
        self.resources = resources
        self.game_data = game_data
        self.ui_components = ui_components
        self.game_state = game_state
        self.text_box_manager = TextBoxManager()

    def draw_text(self, surface, text, color, x, y, font_obj=None):
        """在指定位置绘制文本"""
        if font_obj is None:
            font_obj = self.resources.font
        text_surface = font_obj.render(text, True, color)
        surface.blit(text_surface, (x, y))

    def draw_characters_init(self, screen):
        """初始化绘制角色信息"""
        now = time.time()
        if now - self.game_state.last_cursor_toggle > Constants.CURSOR_TOGGLE_INTERVAL:
            self.game_state.cursor_visible = not self.game_state.cursor_visible
            self.game_state.last_cursor_toggle = now

        if self.game_state.error_message and (
                time.time() - self.game_state.error_message_time) < Constants.ERROR_DISPLAY_TIME:
            error_surface = self.resources.font.render(self.game_state.error_message, True, (255, 0, 0))
            screen.blit(error_surface, (Constants.WIDTH // 2 - error_surface.get_width() // 2, 20))

        for i, data in enumerate(self.game_data.character_data_init):
            # 绘制头像
            screen.blit(self.resources.avatars[i], self.game_data.avatar_positions_one[i])

            # 绘制名字、模型
            self.draw_text(screen, f"名字: {data['name']}", Constants.TEXT_COLOR,
                           self.game_data.avatar_positions_one[i][0], self.game_data.avatar_positions_one[i][1] + 110)
            self.draw_text(screen, f"模型: {data['model']}", Constants.TEXT_COLOR,
                           self.game_data.avatar_positions_one[i][0], self.game_data.avatar_positions_one[i][1] + 140)

            # 计算输入框的起始位置
            input_y = self.game_data.avatar_positions_one[i][1] + 170
            if self.game_state.dropdown_active == i:
                input_y += len(self.game_data.models_init) * 30

            # 绘制弹夹容量文字和数字
            clip_label_x = self.game_data.avatar_positions_one[i][0]
            clip_text_x = clip_label_x + self.resources.font.size("弹夹容量")[0] + 5
            self.draw_text(screen, "弹夹容量", Constants.TEXT_COLOR, clip_label_x, input_y + 5)
            self.draw_text(screen, self.game_data.input_values[i], Constants.TEXT_COLOR, clip_text_x, input_y + 5)
            if self.game_state.input_active == i and self.game_state.cursor_visible:
                pygame.draw.line(screen, Constants.TEXT_COLOR,
                                 (clip_text_x + self.resources.font.size(self.game_data.input_values[i])[0],
                                  input_y + 5),
                                 (clip_text_x + self.resources.font.size(self.game_data.input_values[i])[0],
                                  input_y + 25), 2)

            # 绘制子弹位置文字和数字
            bullet_label_x = self.game_data.avatar_positions_one[i][0]
            bullet_y = input_y + 40
            bullet_text_x = bullet_label_x + self.resources.font.size("子弹位置")[0] + 5
            self.draw_text(screen, "子弹位置", Constants.TEXT_COLOR, bullet_label_x, bullet_y + 5)
            self.draw_text(screen, self.game_data.input_values[i + 4], Constants.TEXT_COLOR, bullet_text_x,
                           bullet_y + 5)
            if self.game_state.input_active == i + 4 and self.game_state.cursor_visible:
                pygame.draw.line(screen, Constants.TEXT_COLOR,
                                 (bullet_text_x + self.resources.font.size(self.game_data.input_values[i + 4])[0],
                                  bullet_y + 5),
                                 (bullet_text_x + self.resources.font.size(self.game_data.input_values[i + 4])[0],
                                  bullet_y + 25), 2)

        # 绘制下拉框（只显示字）
        if self.game_state.dropdown_active is not None:
            dropdown_rect = self.game_data.dropdown_rects[self.game_state.dropdown_active]
            for j, model in enumerate(self.game_data.models_init):
                option_y = dropdown_rect.y + (j + 1) * 30
                self.draw_text(screen, model, Constants.TEXT_COLOR, dropdown_rect.x + 5, option_y + 5)

    def draw_characters_game(self, screen):
        """绘制游戏中的角色信息"""
        for i, data in enumerate(self.game_data.character_data_game):
            pos = self.game_data.avatar_positions_two[i]

            # 布局参数
            AVATAR_HEIGHT = 100  # 头像高度
            LINE_HEIGHT = self.resources.font_small.size("Test")[1] * 1.3
            TEXT_START_Y = pos[1] + AVATAR_HEIGHT + 10
            CARD_ICON_SIZE = (30, 45)  # 手牌图标尺寸
            CARD_START_Y = TEXT_START_Y + LINE_HEIGHT * 4

            # 1. 绘制头像
            screen.blit(self.resources.avatars[i], pos)

            # 2. 绘制玩家名字
            self.draw_text(screen,
                           data['name'],
                           Constants.TEXT_COLOR,
                           pos[0],
                           TEXT_START_Y,
                           self.resources.font_small)

            # 3. 绘制模型名称
            self.draw_text(screen,
                           data['model'],
                           (200, 200, 200),  # 浅灰色
                           pos[0],
                           TEXT_START_Y + LINE_HEIGHT,
                           self.resources.font_small)

            # 4. 绘制子弹信息
            bullet_text = f"子弹: {data['bullet_position_game']}/{data['clip_capacity']}"
            self.draw_text(screen,
                           bullet_text,
                           (255, 215, 0),  # 金色
                           pos[0],
                           TEXT_START_Y + LINE_HEIGHT * 2,
                           self.resources.font_small)

            # 5. 绘制当前位置
            if 'current_position' in data:
                self.draw_text(screen,
                               f"位置: {data['current_position']}",
                               (180, 230, 180),  # 浅绿
                               pos[0],
                               TEXT_START_Y + LINE_HEIGHT * 3,
                               self.resources.font_small)

            # 6. 直接绘制手牌（无标签）
            if 'hand' in data and data['hand']:
                # 计算手牌区域总宽度
                total_cards_width = len(data['hand']) * (CARD_ICON_SIZE[0] + 5) - 5
                card_start_x = pos[0] + (100 - total_cards_width) // 2  # 居中显示

                for j, card in enumerate(data['hand']):
                    # 根据牌型选择不同颜色
                    card_color = {
                        'Q': (255, 50, 50),  # 红色
                        'K': (50, 50, 255),  # 蓝色
                        'A': (50, 200, 50),  # 绿色
                        'Joker': (150, 50, 200)  # 紫色
                    }.get(card, (200, 200, 200))  # 默认灰色

                    # 绘制牌背景
                    card_rect = pygame.Rect(
                        card_start_x + j * (CARD_ICON_SIZE[0] + 5),
                        CARD_START_Y,
                        CARD_ICON_SIZE[0],
                        CARD_ICON_SIZE[1]
                    )
                    pygame.draw.rect(screen, card_color, card_rect)
                    pygame.draw.rect(screen, (0, 0, 0), card_rect, 2)  # 黑色边框

                    # 绘制牌面文字
                    card_font = pygame.font.SysFont(None, 24)
                    card_surface = card_font.render(card, True, (255, 255, 255))
                    screen.blit(
                        card_surface,
                        (card_rect.centerx - card_surface.get_width() // 2,
                         card_rect.centery - card_surface.get_height() // 2)
                    )

    def draw_main_menu(self, screen, mouse_pos):
        """绘制主菜单界面"""
        screen.blit(self.resources.background_main, (0, 0))

        # 绘制主界面按钮文本
        if self.ui_components.button_start.collidepoint(mouse_pos):
            self.draw_text(screen, "开始游戏", Constants.HOVER_COLOR,
                           self.ui_components.button_start.x, self.ui_components.button_start.y)
        else:
            self.draw_text(screen, "开始游戏", Constants.TEXT_COLOR,
                           self.ui_components.button_start.x, self.ui_components.button_start.y)

        if self.ui_components.button_history.collidepoint(mouse_pos):
            self.draw_text(screen, "对局记录", Constants.HOVER_COLOR,
                           self.ui_components.button_history.x, self.ui_components.button_history.y)
        else:
            self.draw_text(screen, "对局记录", Constants.TEXT_COLOR,
                           self.ui_components.button_history.x, self.ui_components.button_history.y)

        if self.ui_components.button_exit.collidepoint(mouse_pos):
            self.draw_text(screen, "退出游戏", Constants.HOVER_COLOR,
                           self.ui_components.button_exit.x, self.ui_components.button_exit.y)
        else:
            self.draw_text(screen, "退出游戏", Constants.TEXT_COLOR,
                           self.ui_components.button_exit.x, self.ui_components.button_exit.y)

    def draw_init_screen(self, screen, mouse_pos):
        """绘制初始化界面"""
        screen.blit(self.resources.background_game, (0, 0))
        self.draw_characters_init(screen)

        # 绘制游戏界面按钮文本
        if self.ui_components.button_random.collidepoint(mouse_pos):
            self.draw_text(screen, "随机", Constants.HOVER_COLOR,
                           self.ui_components.button_random.x, self.ui_components.button_random.y)
        else:
            self.draw_text(screen, "随机", Constants.TEXT_COLOR,
                           self.ui_components.button_random.x, self.ui_components.button_random.y)

        if self.ui_components.button_play.collidepoint(mouse_pos):
            self.draw_text(screen, "进入游戏", Constants.HOVER_COLOR,
                           self.ui_components.button_play.x, self.ui_components.button_play.y)
        else:
            self.draw_text(screen, "进入游戏", Constants.TEXT_COLOR,
                           self.ui_components.button_play.x, self.ui_components.button_play.y)

    def draw_game_screen(self, screen):
        """绘制游戏界面"""
        try:
            screen.blit(self.resources.background_game, (0, 0))
            self.draw_characters_game(screen)
            # 文本框
            self.text_box_manager.draw(screen)
        except KeyboardInterrupt:
            # 用户中断，正常退出
            pygame.quit()
            sys.exit()
        except Exception as e:
            print(f"绘制游戏界面时出错: {e}")